package top.wettis.chat.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.wettis.chat.constant.ResultType;
import top.wettis.chat.mapper.PermissionMapper;
import top.wettis.chat.mapper.UserMapper;
import top.wettis.chat.pojo.DO.User;
import top.wettis.chat.pojo.Query.*;
import top.wettis.chat.pojo.VO.Result;
import top.wettis.chat.service.IUserService;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import static top.wettis.chat.constant.Contant.LOGIN_USER_NAME;


/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author wettis
 * @since 2023-03-25
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService, StpInterface {

    @Autowired
    private UserMapper userMapper;
    private final PermissionMapper permissionMapper;

    public UserServiceImpl(PermissionMapper permissionMapper) {
        this.permissionMapper = permissionMapper;
    }

    @Override
    public SaResult doLogin(UserAccount userAccount) {
        User user = getBaseMapper().selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, userAccount.getName() ));
        if (user != null) {
            if(BCrypt.checkpw(userAccount.getPassword() , user.getPassword())){
                StpUtil.login(user.getUserId());
                String tokenValue = StpUtil.getTokenInfo().getTokenValue();
                return SaResult.data(tokenValue);
            }
            else {
                return SaResult.error("fail");
            }
        } else {
            return SaResult.error("fail");
        }
    }

    @Override
    public Result<Object> isLogin() {
        if (StpUtil.isLogin()){
            return Result.customInfo(200,"已登录",true);
        } else {
            return Result.customInfo(200,"未登录",false);
        }
    }

    @Override
    public Result<Object> logout() {
        if (StpUtil.getLoginIdDefaultNull() != null) {
            return Result.customInfo(200, "成功退出登录",null);
        } else {
            return Result.failInfo(ResultType.LOGIN,null);
        }
    }

    @Override
    public Result<Object> tokenInfo() {
        if (StpUtil.getLoginIdDefaultNull() != null) {
            return Result.customInfo(200, String.valueOf(StpUtil.getTokenInfo()),null);
        } else {
            return Result.failInfo(ResultType.LOGIN,null);
        }
    }

    @Override
    public SaResult register(UserAccount userAccount) {

        try {
            User user = query().eq("username", userAccount.getName()).one();
            if (user != null){
                return null;
            }
            User user1 = new User();
            user1.setUsername(userAccount.getName());
            user1.setPassword(DigestUtil.bcrypt(userAccount.getPassword()));
            user1.setLevel(1);
            user1.setPoint(0.0);
            user1.setConsecutive(0);
            user1.setAsktimes(0);
            user1.setPunchtimes(0);
            user1.setRole("体验用户");
            user1.setPhone("暂未录入");
            user1.setNeckName(LOGIN_USER_NAME + RandomUtil.randomBytes(6));
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String dateTimeString = now.format(formatter);
            user1.setCreateTime(dateTimeString);
            save(user1);
            LoginAccont loginAccont = new LoginAccont();
            User user2 = query().eq("username", userAccount.getName()).one();
            StpUtil.login(user2.getUserId());
            String tokenValue = StpUtil.getTokenInfo().getTokenValue();
            return SaResult.data(tokenValue);
        } catch (Exception e) {
            return SaResult.error("注册失败");
        }

    }

    @Override
    public Result<Object> delete(Integer id) {
        User user = query().eq("user_id", id).one();
        if (user == null){
            return Result.failInfo(ResultType.DELETE,null);
        }
        userMapper.deleteById(id);
        return Result.successInfo(ResultType.DELETE , "删除成功");
    }

    @Override
    public Result<Object> update(UpdateAccont updateAccont) {
        int id = StpUtil.getLoginIdAsInt();
        User user_temp = query().eq("user_id", id).one();
        if (user_temp == null) {
            return Result.successInfo(ResultType.UPDATE , "用户不存在");
        }
        userMapper.updateInfo(id , updateAccont.getNeckName() , updateAccont.getEmail() , updateAccont.getPhone() , DigestUtil.bcrypt(updateAccont.getPassword()));
        return Result.successInfo(ResultType.UPDATE , "修改成功!");
    }

    @Override
    public List<PointOrdAccont> pointOrd() {
        System.out.println(userMapper.pointOrd());
        return userMapper.pointOrd();
    }

    @Override
    public List<ConOrdAccont> ConOrd() {
        System.out.println(userMapper.ConOrd());
        return userMapper.ConOrd();
    }

    @Override
    public List<AskOrdAccont> AskOrd() {
        System.out.println(userMapper.AskOrd());
        return userMapper.AskOrd();
    }

    @Override
    public List<PunchOrdAccont> PunchTmesOrd() {
        System.out.println(userMapper.PunchTmesOrd());
        return userMapper.PunchTmesOrd();
    }

    @Override
    public void askjj(int userId) {

        userMapper.askjj(userId);
    }

    @Override
    public Integer get3(int userId) {
        return userMapper.get3(userId);
    }

    @Override
    public void addPlan(int userId ,String time) {
        userMapper.addPlan(userId , time);
    }

    @Override
    public User getUser(int id) {
        return userMapper.selectById(id);
    }


    @Override
    public List<String> getPermissionList(Object o, String s) {
        return null;
    }

    @Override
    public List<String> getRoleList(Object o, String s) {
        // 获取当前用户的角色信息
        String userPermission = permissionMapper.selectById(
                StpUtil.getLoginIdAsInt())
                .getName();
        return new ArrayList<>(){{
            add(userPermission);
        }};
    }


    public String selectTiime(int id) {
        return userMapper.selectTiime(id);
    }
}
